<template>
  <div class="tags">
    <div ref="content" class="main">
      <el-tag :data-id="item.id" class="" v-for="item in $data.models" :key="item.id" @dblclick="jumpToModel(item.id)">
        {{ item.name }}
      </el-tag>
    </div>

      <input-table v-model="$data.apis"  class="apis"></input-table>

  </div>
</template>

<script setup>
import Sortable from 'sortablejs'



defineOptions({
  name: "models",
  inheritAttrs: true,
});

//定义 vue2的this,当前组件
let $self = getCurrentInstance();

//定义 $attrs
let $attrs = useAttrs()


//定义事件
let $emit = defineEmits(["update:modelValue", "countChange"]);

const jumpToModel = id => {
  jv.$router.push("/dev/data-model/edit/" + id)
}
//定义属性
var $props = defineProps({});
var $model = defineModel({type: Object});

//定义data
let $data = reactive({
  models: [],
  $apis:[]
})


const content = ref();

let left;

const initSort = () => {
  left && left.destroy();
  left = new Sortable(content.value, {
    group: {
      name: 'shared',
    },
    animation: 150,
    disabled: !($model.value && $model.value.id),
    onAdd: evt => {
      var id = evt.item.dataset.id;

      jv.$http.post("/dev/data-model-tree/add-model/" + $model.value.id + "/" + id).then(res => {

        var list = res.data.data;
        $emit("countChange", list)
      });
      // var oriIds = $data.models.map(it => it.id);
      // if (oriIds.includes(id)) {
      //   evt.returnValue = false;
      //   return false;
      // }
    },
    onRemove: evt => {
      var id = evt.item.dataset.id;
      jv.$http.post("/dev/data-model-tree/remove-model/" + $model.value.id + "/" + id).then(res => {

        var list = res.data.data;
        $emit("countChange", list)
      });
    },
    onSort: evt => {
      var typeId = $model.value;
      var oriIds = $data.models.map(it => it.id);
      var ids = left.toArray();


    }
  });
}

const loadDetail = () => {

  if (!$model.value.id) {
    return;
  }

  jv.$http.post("/dev/data-model-tree/detail/" + $model.value.id).then(res => {
    $data.models = res.data.data.models;
  })

  initSort();
}


watch(() => $model.value, v => {
  nextTick(loadDetail);
}, {immediate: true});


</script>

<style scoped lang="scss">

.tags {
  display: flex;
  flex: 1;
  flex-direction: column;
}

.main {
  padding: 12px;
  min-height: 200px;
  align-content: flex-start;
  gap: 12px;
  display: flex;
}

.apis{
  flex:1;
  margin: 10px;
}
::v-deep(.el-tag) {
  padding: 16px 12px;
  zoom: 1.1;
  cursor: default;
}


::v-deep([data-stage]) {
  background-color: #dbdbdb;
  color: gray;
  border-color: #bbbbbb;
}

.sortable-chosen {
  color: blue !important;
}
</style>